#!/bin/bash

CONFIG=makedist.config

if [ ! -f $CONFIG ]; then
    echo Configuration missing: $CONFIG
    echo Please set the following variables in $CONFIG
    echo in you current directory:
    echo
    echo 'VERSION=x.y.z   #use desired version'
    echo 'BRANCH="develop" #or e.g. "maintained-release"'
    exit
else    
    . $CONFIG
fi    

# Init
OLDDIR=$(pwd)
SRCDIR=$OLDDIR/vym
TMPDIR=$OLDDIR/tmp

echo "Getting sources for: vym"  
echo "             Branch: $BRANCH"
echo "             Branch: $VERSION"
echo "  Working directory: $OLDDIR"
echo 


if [ -d $TMPDIR ]; then
    read -n 1 -p "$TMPDIR exists: Remove it first? [y]" INPUT
    if [ ! "$INPUT" = "n" ]; then
	rm -rf $TMPDIR
    fi	
fi
echo
mkdir $TMPDIR

read -n 1 -p "Pull from git repository ? [y]" INPUT
DO_CHECKOUT=1
if [ "$INPUT" = "n" ]; then
    DO_CHECKOUT=0
fi	
echo

#read -n 1 -p "Create Documentation? [y]" INPUT
#DO_DOCS=1
#if [ "$INPUT" = "n" ]; then
#    DO_DOCS=0
#fi	
#echo

read -n 1 -p "Create Tarball? [y]" INPUT
DO_TARBALL=1
if [ "$INPUT" = "n" ]; then
    DO_TARBALL=0
fi	
echo

echo -n "Remove unpacked sources after creating tarball? [y]"
#echo "(do this before  \"osc addremove\")"
read -n 1 INPUT
DO_REMOVE=1
if [ "$INPUT" = "n" ]; then
    DO_REMOVE=0
fi	
echo

# get data from repository
if [ $DO_CHECKOUT = 1 ]; then
    cd $OLDDIR
    echo Removing $SRCDIR...
    rm -rf $SRCDIR
#    git clone -b $BRANCH git://git.code.sf.net/p/vym/code src
    git clone -b $BRANCH git@github.com:insilmaril/vym.git vym
fi	

#VERSION=$(grep __VYM_VERSION $SRCDIR/version.h |  sed -e 's/^.*\"\(.*\)\"$/\1/g')
TARBALLSRC=vym-$VERSION
echo
echo "Setting version from sources: $VERSION"
echo

# create documentation
#if [ $DO_DOCS = 1 ] ; then
#    cp -ra $SRCDIR/tex $TMPDIR
#    cp -ra $SRCDIR/icons $TMPDIR
#    cp -ra $SRCDIR/flags $TMPDIR
#    cd $TMPDIR/tex
#    for i in {1..3} ; do
#	pdflatex vym.tex
#	pdflatex vym_es.tex
#	pdflatex vym_fr.tex
#	sleep 1
#    done	
#    cd $OLDDIR
#fi

cd $OLDDIR

# create tarball
if [ $DO_TARBALL = 1 ]; then
    if [ -d $TARBALLSRC ] ;  then
	rm -rf $TARBALLSRC
    fi
    cp -ra $SRCDIR $TARBALLSRC

    # Copy doc
    mkdir -p $TARBALLSRC/doc
    cp $TMPDIR/tex/*.pdf $TARBALLSRC/doc

    rm -rf $TARBALLSRC/.git
    tar cvjf vym-$VERSION.tar.bz2 $TARBALLSRC
    if [ $DO_REMOVE = 1 ]; then
	rm -rf $TARBALLSRC
    fi
fi
